package common

import (
	"context"
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strconv"

	my "renting-demo/model/mysql"
	"strings"
)

var es *elasticsearch.Client
var err error
var db *gorm.DB

func init() {
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://localhost:9200",
		},
	}
	es, err = elasticsearch.NewClient(cfg)
	if err != nil {
		return
	}
	dns := "root:root@tcp(127.0.0.1:3306)/zhuangao"
	db, _ = gorm.Open(mysql.Open(dns), &gorm.Config{})
}

// TODO:添加
func AddTextEsSearch(body, index, id string) {
	req := esapi.IndexRequest{
		Index:        index,
		DocumentType: "_doc",
		DocumentID:   id,
		Body:         strings.NewReader(body),
		Refresh:      "true",
	}
	res, _ := req.Do(context.Background(), es)
	logs.Info(res)
}

// TODO：添加数据
func ToEs() {
	p := []my.Product{}
	db.Find(&p)
	for _, product := range p {
		indec := "product"
		b, _ := json.Marshal(product)
		AddTextEsSearch(string(b), indec, strconv.Itoa(int(product.ID)))
	}
}

func Light() {
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"content": "你好",
			},
		},
		"highlight": map[string]interface{}{
			"fields": map[string]interface{}{
				"content": map[string]interface{}{},
			},
		},
	}
	a, _ := json.Marshal(query)
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("product"),
		es.Search.WithBody(strings.NewReader(string(a))),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithFrom(0),
		es.Search.WithSize(15),
		es.Search.WithPretty(),
	)
	if err != nil {
		return
	}
	defer res.Body.Close()
	logs.Info(res)
}
